<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input
        clearable
        placeholder="请输入内容"
        v-model="form.name"
        class="search-main"
      />
      <el-button type="primary" @click="chaxun">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="addqy">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="tabledata"
        @expand-change="expandHandle"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-table :data="row.rentList">
              <el-table-column
                label="租赁楼宇"
                width="320"
                prop="buildingName"
              />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.status == 0">待生效</el-tag>
                  <el-tag v-if="scope.row.status == 1">生效中</el-tag>
                  <el-tag v-if="scope.row.status == 2">已到期</el-tag>
                  <el-tag v-if="scope.row.status == 3">已退租</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click="xuzu(scope.row)"
                    v-if="scope.row.renewFlag == true"
                    >续租</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    @click="tuizu(scope.row)"
                    v-if="scope.row.exitFlag == true"
                    >退租</el-button
                  >
                  <el-button size="mini" type="text" @click="shanchuzl(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="mini" type="text" @click="addht(scope.row.id)"
              >添加合同</el-button
            >
            <el-button size="mini" type="text" @click="chakan(scope.row.id)"
              >查看</el-button
            >
            <el-button size="mini" type="text" @click="edit(scope.row.id)"
              >编辑</el-button
            >
            <el-button size="mini" type="text" @click="shanchu(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="form.page"
        :page-size="form.pageSize"
      />
    </div>

    <el-dialog
      title="添加合同"
      :visible="rentDialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <!-- 表单区域 -->
      <div class="form-container">
        <el-form
          ref="ruleForm"
          :model="rentForm"
          :rules="rentRules"
          label-position="top"
        >
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select
              v-model="rentForm.buildingId"
              @change="selectbuilding"
              placeholder="请选择"
              :disabled="zldisable"
            >
              <el-option
                v-for="item in lylist"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              @blur="changerent"
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              action="#"
              :http-request="uploadhandle"
              :before-upload="beforUpload"
              :limit="1"
              accept=".doc,.docx,.pdf"
              :file-list="fileList"
            >
              <el-button size="small" type="primary" plain
                >上传合同文件</el-button
              >
              <div slot="tip" class="el-upload__tip">
                支持扩展名：.doc .docx .pdf, 文件大小不超过5M
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="submit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import {
  qylb,
  qylylist,
  qyshanchu,
  uploadAPI,
  addht,
  rentshanchu,
  renttuizu,
  rentlist,
} from "@/api/user";
export default {
  data() {
    return {
      form: {
        page: 1,
        pageSize: 10,
      },
      lylist: [],
      zldisable:false,
      fileList: [],
      rentRules: {
        buildingId: [
          { required: true, message: "请选择楼宇", trigger: "change" },
        ],
        rentTime: [{ required: true, message: "请选择", trigger: "blur" }],
        contractId: [
          { required: true, message: "请上传合同", trigger: "blur" },
        ],
      },
      rentForm: {
        contractId: "",
      },
      total: 0,
      tabledata: [],
      rentDialogVisible: false,
    };
  },
  mounted() {
    this.getdata();
    this.getly();
  },
  methods: {
    changerent(e) {
      this.$forceUpdate();
    },
    selectbuilding(e) {
      console.log(e, "e");
      this.$forceUpdate();
    },
    xuzu(row) {
      console.log(row, "row");
      this.rentDialogVisible = true;
      this.rentForm = {
        contractId: "",
      };
      this.zldisable=true
      this.fileList=[]
      const givenDate = new Date(row.endTime);
      givenDate.setDate(givenDate.getDate() + 1);

      const nextDay = givenDate.toISOString().slice(0, 10);
      console.log(nextDay, "nexday");
      this.rentForm.rentTime = [nextDay,nextDay];

      this.rentForm.buildingId = row.buildingId;
      this.rentForm.enterpriseId = row.enterpriseId;
      this.rentForm.type = 1;
    },
    async expandHandle(row) {
      console.log(row);
      const res = await rentlist(row.id);
      console.log(res, "res");
      row.rentList = res.data;
      row.rentList.forEach((el) => {
        el.enterpriseId = row.id;
      });
      console.log(row.rentList);
    },
    submit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.rentForm.startTime = this.rentForm.rentTime[0];
          this.rentForm.endTime = this.rentForm.rentTime[1];
          delete this.rentForm.rentTime;
          const res = await addht(this.rentForm);
          console.log(res);
          if (res.code == 10000) {
            this.$message.success("成功");
            this.rentDialogVisible = false;
          }
        }
      });
    },
    beforUpload() {},
    async uploadhandle(data) {
      console.log(data, "data");
      const file = data.file;
      const formData = new FormData();
      formData.append("file", file);
      formData.append("type", "contract");
      const res = await uploadAPI(formData);
      console.log(res, "resss");
      this.rentForm.contractId = res.data.id;
      this.rentForm.contractUrl = res.data.url;
      console.log(this.rentForm.contractId);
      this.$refs.ruleForm.validateField("contractId");
    },
    async getly() {
      const res = await qylylist();
      console.log(res, "resss");
      this.lylist = res.data;
    },
    addht(id) {
      this.rentDialogVisible = true;
      this.rentForm = {
        contractId: "",
      };
      this.zldisable=false
      this.rentForm.enterpriseId = id;
      this.rentForm.type = 0;
    },
    closeDialog() {
      this.rentDialogVisible = false;
    },
    tuizu(row){
      this.$confirm("退租不可撤回，是否确认退租当前楼宇?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await renttuizu(row.id);
          if (res.code == 10000) {
            this.$message({
              type: "success",
              message: "退租成功!",
            });
            this.getdata();
          } else {
            this.$message({
              type: "info",
              message: res.msg,
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    shanchuzl(id){
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await rentshanchu(id);
          if (res.code == 10000) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getdata();
          } else {
            this.$message({
              type: "info",
              message: res.msg,
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    shanchu(id) {
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await qyshanchu(id);
          if (res.code == 10000) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getdata();
          } else {
            this.$message({
              type: "info",
              message: res.msg,
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    chakan(id) {
      this.$router.push({
        path: "/enterprisexq",
        query: {
          id: id,
        },
      });
    },
    addqy() {
      this.$router.push({
        path: "/addenterprise",
      });
    },
    edit(id) {
      this.$router.push({
        path: "/addenterprise",
        query: {
          id: id,
        },
      });
    },
    chaxun() {
      this.form.page = 1;
      this.form.pageSize = 10;
      this.getdata();
    },
    handleSizeChange(e) {
      this.form.pageSize = e;
      this.getdata();
    },
    handleCurrentChange(e) {
      this.form.page = e;
      this.getdata();
    },
    async getdata() {
      const res = await qylb(this.form);
      console.log(res, "res");
      this.tabledata = res.data.rows.map((item) => {
        return {
          ...item,
          rentList: [], // 每一行补充存放合同的列表
        };
      });
      this.total = res.data.total;
    },
  },
};
</script>
<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container {
  margin: 10px 0px;
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
.form-container {
  padding: 0px 80px;
}
.building-container {
  background: #fff;
  padding: 20px;
  box-sizing: border-box;
}
</style>
